package com.example.forumadminbackend.controller;

import com.example.forumadminbackend.entity.Admin;
import com.example.forumadminbackend.entity.User;
import com.example.forumadminbackend.entity.Post;
import com.example.forumadminbackend.entity.Comment;
import com.example.forumadminbackend.service.AdminService;
import com.example.forumadminbackend.service.WordService;
import com.example.forumadminbackend.mapper.UserMapper;
import com.example.forumadminbackend.mapper.PostMapper;
import com.example.forumadminbackend.mapper.CommentMapper;
import com.example.forumadminbackend.util.JwtUtil;
import com.example.forumadminbackend.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import com.example.forumadminbackend.dto.*;

@RestController
@RequestMapping("/adminapi")
@Tag(name = "管理员接口")
public class AdminApiController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private WordService wordService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;

    @PostMapping("/login")
    @Operation(summary = "管理员登录", description = "返回JWT token。示例：Bearer eyJhbGciOiJIUzI1NiJ9...")
    public ResponseEntity<Result<String>> login(@RequestBody AdminLoginDTO loginDTO) {
        Admin admin = adminService.login(loginDTO.getUsername(), loginDTO.getPassword());
        if (admin != null) {
            return ResponseEntity.ok(Result.success(JwtUtil.generateToken(admin.getAdminId(), admin.getUsername())));
        }
        return ResponseEntity.status(400).body(Result.fail("用户名或密码错误"));
    }

    // 用户管理
    @GetMapping("/users")
    @Operation(summary = "查看所有用户", description = "返回用户列表")
    public Result<List<User>> listUsers() {
        return Result.success(userMapper.selectAll());
    }

    @PostMapping("/user/ban")
    @Operation(summary = "封禁用户", description = "将用户状态设为0（封禁）")
    public ResponseEntity<Result<String>> banUser(@RequestBody UserIdDTO dto) {
        User user = userMapper.selectById(dto.getUserId());
        if (user == null) {
            return ResponseEntity.status(400).body(Result.fail("用户不存在"));
        }
        if (user.getStatus() != null && user.getStatus() == 0) {
            return ResponseEntity.status(400).body(Result.fail("该用户已被封禁"));
        }
        userMapper.updateStatus(dto.getUserId(), 0);
        return ResponseEntity.ok(Result.success("封禁成功"));
    }

    @PostMapping("/user/unban")
    @Operation(summary = "解封用户", description = "将用户状态设为1（正常）")
    public ResponseEntity<Result<String>> unbanUser(@RequestBody UserIdDTO dto) {
        User user = userMapper.selectById(dto.getUserId());
        if (user == null) {
            return ResponseEntity.status(400).body(Result.fail("用户不存在"));
        }
        if (user.getStatus() != null && user.getStatus() == 1) {
            return ResponseEntity.status(400).body(Result.fail("该用户未被封禁"));
        }
        userMapper.updateStatus(dto.getUserId(), 1);
        return ResponseEntity.ok(Result.success("解封成功"));
    }

    // 帖子管理
    @GetMapping("/posts")
    @Operation(summary = "查看所有帖子", description = "返回帖子列表")
    public Result<List<Post>> listPosts() {
        return Result.success(postMapper.selectAll());
    }

    @PostMapping("/post/delete")
    @Operation(summary = "删除帖子", description = "根据postId删除帖子")
    public ResponseEntity<Result<String>> deletePost(@RequestBody PostIdDTO dto) {
        Post post = postMapper.selectById(dto.getPostId());
        if (post == null) {
            return ResponseEntity.status(400).body(Result.fail("帖子不存在"));
        }
        postMapper.delete(dto.getPostId());
        return ResponseEntity.ok(Result.success("删除成功"));
    }

    @PostMapping("/post/top")
    @Operation(summary = "置顶帖子", description = "将is_top设为1")
    public ResponseEntity<Result<String>> topPost(@RequestBody PostIdDTO dto) {
        Post post = postMapper.selectById(dto.getPostId());
        if (post == null) {
            return ResponseEntity.status(400).body(Result.fail("帖子不存在"));
        }
        if (post.getIsTop() != null && post.getIsTop() == 1) {
            return ResponseEntity.status(400).body(Result.fail("该帖子已置顶"));
        }
        postMapper.updateTop(dto.getPostId(), 1);
        return ResponseEntity.ok(Result.success("置顶成功"));
    }

    @PostMapping("/post/untop")
    @Operation(summary = "取消置顶帖子", description = "将is_top设为0")
    public ResponseEntity<Result<String>> untopPost(@RequestBody PostIdDTO dto) {
        Post post = postMapper.selectById(dto.getPostId());
        if (post == null) {
            return ResponseEntity.status(400).body(Result.fail("帖子不存在"));
        }
        if (post.getIsTop() != null && post.getIsTop() == 0) {
            return ResponseEntity.status(400).body(Result.fail("该帖子未置顶"));
        }
        postMapper.updateTop(dto.getPostId(), 0);
        return ResponseEntity.ok(Result.success("取消置顶成功"));
    }

    @PostMapping("/post/essence")
    @Operation(summary = "加精帖子", description = "将is_精华设为1")
    public ResponseEntity<Result<String>> essencePost(@RequestBody PostIdDTO dto) {
        Post post = postMapper.selectById(dto.getPostId());
        if (post == null) {
            return ResponseEntity.status(400).body(Result.fail("帖子不存在"));
        }
        if (post.getIs精华() != null && post.getIs精华() == 1) {
            return ResponseEntity.status(400).body(Result.fail("该帖子已加精"));
        }
        postMapper.update精华(dto.getPostId(), 1);
        return ResponseEntity.ok(Result.success("加精成功"));
    }

    @PostMapping("/post/unessence")
    @Operation(summary = "取消加精帖子", description = "将is_精华设为0")
    public ResponseEntity<Result<String>> unessencePost(@RequestBody PostIdDTO dto) {
        Post post = postMapper.selectById(dto.getPostId());
        if (post == null) {
            return ResponseEntity.status(400).body(Result.fail("帖子不存在"));
        }
        if (post.getIs精华() != null && post.getIs精华() == 0) {
            return ResponseEntity.status(400).body(Result.fail("该帖子未加精"));
        }
        postMapper.update精华(dto.getPostId(), 0);
        return ResponseEntity.ok(Result.success("取消加精成功"));
    }

    // 评论管理
    @GetMapping("/comments")
    @Operation(summary = "查看所有评论", description = "返回评论列表")
    public Result<List<Comment>> listComments() {
        return Result.success(commentMapper.selectAll());
    }

    @PostMapping("/comment/delete")
    @Operation(summary = "删除评论", description = "根据commentId删除评论")
    public ResponseEntity<Result<String>> deleteComment(@RequestBody CommentIdDTO dto) {
        Comment comment = commentMapper.selectById(dto.getCommentId());
        if (comment == null) {
            return ResponseEntity.status(400).body(Result.fail("评论不存在"));
        }
        int affected = commentMapper.delete(dto.getCommentId());
        if (affected > 0) {
            return ResponseEntity.ok(Result.success("删除成功"));
        } else {
            return ResponseEntity.status(400).body(Result.fail("评论不存在或已删除"));
        }
    }

    // 管理员通知
    @PostMapping("/notice")
    @Operation(summary = "管理员通知（发帖）", description = "管理员发布通知，所有用户可见。通知即特殊类型的帖子，postType=notice，category=notice，userId为管理员ID。")
    public Result<String> sendNotice(@RequestBody NoticeDTO dto) {
        Post post = new Post();
        post.setPostId(java.util.UUID.randomUUID().toString().replace("-", ""));
        post.setTitle(dto.getTitle());
        post.setContent(dto.getContent());
        post.setPostType("notice");
        post.setCategory("notice");
        post.setUserId(dto.getAdminId());
        post.setViewCount(0);
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setIsTop(1); // 通知默认置顶
        post.setIs精华(1); // 通知默认加精
        post.setCreateTime(new java.util.Date());
        post.setUpdateTime(new java.util.Date());
        postMapper.insert(post);
        return Result.success("通知发布成功");
    }

    // 违禁词管理
    @PostMapping("/word/add")
    @Operation(summary = "添加违禁词", description = "添加一个违禁词到words.txt")
    public ResponseEntity<Result<String>> addWord(@RequestBody WordDTO dto) throws IOException {
        String result = wordService.addWord(dto.getWord());
        if ("添加成功".equals(result)) {
            return ResponseEntity.ok(Result.success(result));
        } else {
            return ResponseEntity.status(400).body(Result.fail(result));
        }
    }

    @PostMapping("/word/update")
    @Operation(summary = "修改违禁词", description = "将旧违禁词修改为新违禁词")
    public ResponseEntity<Result<String>> updateWord(@RequestBody UpdateWordDTO dto) throws IOException {
        String result = wordService.updateWord(dto.getOldWord(), dto.getNewWord());
        if ("修改成功".equals(result)) {
            return ResponseEntity.ok(Result.success(result));
        } else {
            return ResponseEntity.status(400).body(Result.fail(result));
        }
    }

    @PostMapping("/word/delete")
    @Operation(summary = "删除违禁词", description = "删除指定违禁词")
    public ResponseEntity<Result<String>> deleteWord(@RequestBody WordDTO dto) throws IOException {
        boolean deleted = wordService.deleteWord(dto.getWord());
        if (deleted) {
            return ResponseEntity.ok(Result.success("删除成功"));
        } else {
            return ResponseEntity.status(400).body(Result.fail("未找到该词"));
        }
    }

    @GetMapping("/words")
    @Operation(summary = "查看所有违禁词", description = "返回所有违禁词列表")
    public Result<List<String>> getAllWords() throws IOException {
        return Result.success(wordService.getAllWords());
    }
} 